package handler

import (
	"github.com/eatmoreapple/openwechat"
	"log"
	"strings"
	"wechat/gpt/client/api"
)

type userMessageHandler struct {
}

// NewUserMessageHandler 创建私聊处理器
func NewUserMessageHandler() IMessageHandler {
	return &userMessageHandler{}
}

func (this *userMessageHandler) handle(message *openwechat.Message) error {
	if message.IsText() {
		return this.replyText(message)
	}
	return nil
}

func (this *userMessageHandler) replyText(msg *openwechat.Message) error {
	// 接收私聊消息
	sender, err := msg.Sender()
	log.Printf("received from : %v\nmessage : %v", sender.NickName, msg.Content)
	if userSession.ClearUserSessionContext(sender.ID(), msg.Content) {
		_, err = msg.ReplyText("上下文已清空")
		if err != nil {
			log.Printf("response user error: %v \n", err)
			return err
		}
		return nil
	}

	// 整理数据
	requestText := strings.TrimSpace(msg.Content)
	requestText = strings.Trim(msg.Content, "\n")

	// 读取缓存
	requestText = userSession.GetUserSessionContext(sender.ID()) + requestText

	// 询问gpt
	res, err := api.Call(requestText)
	if err != nil {
		log.Printf("call gpt error : %v\n", err)
		msg.ReplyText("出现错误")
		return err
	}

	// 如果询问结果为空则直接返回
	if res == "" {
		return nil
	}

	// 整理数据
	res = strings.TrimSpace(res)
	res = strings.Trim(res, "\n")

	// 设置上下文缓存
	userSession.SetUserSessionContext(sender.ID(), requestText, res)

	// 回复用户
	res = "本消息由ChatGPT回复\n\n" + res
	_, err = msg.ReplyText(res)
	if err != nil {
		log.Printf("reply friend error : %v\n", err)
	}

	return err
}
